package UI.Main;

import BLL.FileDelete;
import UI.Main.*;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

/**
 * @author 杨明政
 * @version  2021.0610
 * @since 1.8
 */


/**
 * 左侧用户边栏.
 * For example:
 * <pre>
 * UserPage u=new UserPage();
 * </pre>
 * @author 杨明政
 * @see javax.swing.JComponent
 * @see javax.swing.JPanel
 */
public class UserPage extends JPanel implements ActionListener {
    public static UserPage _instance;
    JButton mainpagebtn,searchpagebtn,copybtn,trans,server;
    JLabel port;
    public GetThread myThread;
    public static int isServing=-1;
    public static boolean isSearch=false;
    public static boolean serverFlag=false;
    /**
     * 用户边栏构造函数
     */
    public UserPage()
    {
        this._instance=this;
        this.setLayout(null);
        this.setBackground(Color.DARK_GRAY);
        mainpagebtn=new JButton("主页");
        this.add(mainpagebtn);
        mainpagebtn.addActionListener(this);
        mainpagebtn.setBounds(0,300,200,50);
        mainpagebtn.setFont(new  java.awt.Font("宋体",  1,  28));
        mainpagebtn.setForeground(Color.black);
        mainpagebtn.setBackground(Color.lightGray);

        searchpagebtn=new JButton("搜索");
        this.add(searchpagebtn);
        searchpagebtn.addActionListener(this);
        searchpagebtn.setBounds(0,350,200,50);
        searchpagebtn.setFont(new  java.awt.Font("宋体",  1,  28));
        searchpagebtn.setForeground(Color.white);
        searchpagebtn.setBackground(Color.darkGray);

        copybtn=new JButton("批量复制");
        this.add(copybtn);
        copybtn.addActionListener(this);
        copybtn.setBounds(0,600,200,50);
        copybtn.setFont(new  java.awt.Font("宋体",  1,  28));
        copybtn.setForeground(Color.white);
        copybtn.setBackground(Color.darkGray);

        trans=new JButton("上传");
        this.add(trans);
        trans.addActionListener(this);
        trans.setBounds(0,650,200,50);
        trans.setFont(new  java.awt.Font("宋体",  1,  28));
        trans.setForeground(Color.white);
        trans.setBackground(Color.darkGray);

        server=new JButton("接收");
        this.add(server);
        server.addActionListener(this);
        server.setBounds(0,700,200,50);
        server.setFont(new  java.awt.Font("宋体",  1,  28));
        server.setForeground(Color.white);
        server.setBackground(Color.darkGray);
    }
    /**
     * 动作处理
     * @param e 动作事件
     */
    @Override
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==mainpagebtn)
        {
            Frame.pages.first(Frame.mainPanel);
            mainpagebtn.setBackground(Color.lightGray);
            mainpagebtn.setForeground(Color.black);
            searchpagebtn.setBackground(Color.darkGray);
            searchpagebtn.setForeground(Color.white);
            isSearch=false;
            return;
        }
        if(e.getSource()==searchpagebtn)
        {
            isSearch=true;
            Frame.pages.first(Frame.mainPanel);
            Frame.pages.next(Frame.mainPanel);
            searchpagebtn.setBackground(Color.lightGray);
            mainpagebtn.setForeground(Color.white);
            mainpagebtn.setBackground(Color.darkGray);
            searchpagebtn.setForeground(Color.black);
        }
        if(e.getSource()==copybtn)
        {
            String path="";
            JFrame chatFrame=new JFrame();
            JFileChooser fileChooser = new JFileChooser();
            FileSystemView fsv = FileSystemView.getFileSystemView();
            System.out.println(fsv.getHomeDirectory());
            fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
            fileChooser.setDialogTitle("请选择复制到的文件夹");
            fileChooser.setApproveButtonText("确定");
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int result=0;
            result = fileChooser.showOpenDialog(chatFrame);
            if (JFileChooser.APPROVE_OPTION == result) {
                path=fileChooser.getSelectedFile().getPath();
                System.out.println("path: "+path);
            }
            List<String> selected_str;
            if(isSearch)
            {
                selected_str = SearchPage.list.getSelectedValuesList();
            }
            else
            {
               selected_str = MainForm.list.getSelectedValuesList();
            }

            if(selected_str.size()==0)
            {
                JOptionPane.showMessageDialog(
                        this,
                        "At least one file",
                        "ERROR",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            File file;
            File aim=new File(path);
            int num = selected_str.size();
            if(isSearch){//如果是正在搜索，从Maps取URL
                for(int i = 0; i < selected_str.size(); ++i){
                    file = new File(SearchPage.mapSearch.get(selected_str.get(i)));
                    if(file.isDirectory())
                        continue;
                    String newFileName = SearchPage.mapSearch.get(selected_str.get(i)).substring(SearchPage.mapSearch.get(selected_str.get(i)).lastIndexOf("\\")+1); //目标文件地址
                    String desPathStr = path + File.separator + newFileName; //源文件地址
                    try
                    {
                        FileInputStream fis = new FileInputStream(SearchPage.mapSearch.get(selected_str.get(i)));//创建输入流对象
                        FileOutputStream fos = new FileOutputStream(desPathStr); //创建输出流对象
                        byte datas[] = new byte[1024*8];//创建搬运工具
                        int len = 0;//创建长度
                        while((len = fis.read(datas))!=-1)//循环读取数据
                        {
                            fos.write(datas,0,len);
                        }
                        fis.close();//释放资源
                        fis.close();//释放资源
                    }
                    catch (Exception e1)
                    {
                        e1.printStackTrace();
                    }
                }
            }else{//否则就用Cur_URL拼接获得
                for(int i = 0; i < selected_str.size(); ++i){
                    file = new File(MainForm.Cur_URL + selected_str.get(i) +  "\\");
                    if(file.isDirectory())
                        continue;
                    String src=MainForm.Cur_URL + selected_str.get(i);
                    String newFileName = src.substring(src.lastIndexOf("\\")+1); //目标文件地址
                    System.out.println("源文件:"+newFileName);
                    String desPathStr = path + File.separator + newFileName; //源文件地址
                    System.out.println("目标文件地址:"+desPathStr);
                    try
                    {
                        FileInputStream fis = new FileInputStream(src);//创建输入流对象
                        FileOutputStream fos = new FileOutputStream(desPathStr); //创建输出流对象
                        byte datas[] = new byte[1024*8];//创建搬运工具
                        int len = 0;//创建长度
                        while((len = fis.read(datas))!=-1)//循环读取数据
                        {
                            fos.write(datas,0,len);
                        }
                        fis.close();//释放资源
                        fis.close();//释放资源
                    }
                    catch (Exception e1)
                    {
                        e1.printStackTrace();
                    }
                }
            }
        }
        if(e.getSource()==trans)
        {
            String ip = null;
            int portnum = 0;
            String str = JOptionPane.showInputDialog(this,"请输接ip","输入ip",JOptionPane.PLAIN_MESSAGE);
            if (str != null){
                try{
                    ip=str;
                }
                catch (Exception e1){
                    e1.printStackTrace();
                }
            }
            else
                return;
            String str2 = JOptionPane.showInputDialog(this,"请输发出端口号","发出端口号",JOptionPane.PLAIN_MESSAGE);
            if (str2 != null){
                try{
                    portnum = Integer.parseInt(str2);
                }
                catch (Exception e1){
                    e1.printStackTrace();
                }
            }
            String path="";
            JFrame chatFrame=new JFrame();
            JFileChooser fileChooser = new JFileChooser();
            FileSystemView fsv = FileSystemView.getFileSystemView();
            System.out.println(fsv.getHomeDirectory());
            fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
            fileChooser.setDialogTitle("请选择需要传输的文件");
            fileChooser.setApproveButtonText("确定");
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int result=0;
            result = fileChooser.showOpenDialog(chatFrame);
            if (JFileChooser.APPROVE_OPTION == result) {
                path=fileChooser.getSelectedFile().getPath();
                System.out.println("path: "+path);
            }
            try {
                FileTransferClient client = new FileTransferClient(ip,portnum); // 启动客户端连接
                client.sendFile(path); // 传输文件
            } catch (Exception e3) {
                e3.printStackTrace();
            }
        }
        if(e.getSource()==server)
        {
            int portnum = 0;
            isServing*=-1;
            if(isServing==1)
            {
                String str = JOptionPane.showInputDialog(this,"请输接收端口号","输入端口号",JOptionPane.PLAIN_MESSAGE);
                if (str != null){
                    try{
                        portnum = Integer.parseInt(str);
                    }
                    catch (Exception e1){
                        e1.printStackTrace();
                    }
                }
                serverFlag=true;
                myThread=new GetThread(portnum);
                myThread.start();
                server.setBackground(Color.lightGray);
                server.setForeground(Color.black);

            }
            else
            {
                serverFlag=false;
                server.setForeground(Color.white);
                server.setBackground(Color.darkGray);
            }
        }
        return;
    }
}
/**
 * 接受文件服务器线程.
 * For example:
 * <pre>
 * GetThread thread=new GetThread(port);
 * </pre>
 * @author 杨明政
 * @see javax.swing.JComponent
 * @see javax.swing.JPanel
 */
class GetThread extends Thread{
    public int port;
    public FileTransferServer servers;
    /**
     * 生成线程
     * @param port 目标端口
     */
    public GetThread(int port)
    {
        this.port=port;
    }
    @Override
    public void run(){
        try {
            servers = new FileTransferServer(port); // 启动服务端
            servers.load();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
